import { axios } from "../../utils/request";

// pages/userEditor/userEditor.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar:'',
    nickName:"",
    name:""
  },
  async init(){
   let userInfo = wx.getStorageSync('userInfo')
   let { avatar,nickName } = userInfo
    this.setData({
      avatar,
      nickName
    })
  },
  onChange(e:any){
    const value = e.detail
    this.setData({
      name:value
    })
  },
  async chooseAvatar(){
   try {
      let fileData = await wx.chooseMedia({ 
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        camera: 'front',
      })
      let tempPath = fileData.tempFiles[0].tempFilePath
      let openId = wx.getStorageSync('token')
      wx.showToast({
        title:"正在上传",
        icon:'loading'
      })
      wx.uploadFile({
        url: 'https://www.tinyxu.fun/api/user/avatar',
        filePath: tempPath,
        name: 'avatar',
        formData: { openId },
        success:(res:any) =>{
          let userInfo = JSON.parse(res.data).data[0]
          wx.setStorageSync("userInfo",userInfo)
          this.init()
          wx.hideLoading()
        },
      });
   } catch (error) {
    wx.showToast({
      title:"上传失败",
      icon:'error'
    })
   }
  },
  async changeName(){
    let nickName = this.data.name
    if(nickName){
      let result = await axios("/user/nickName","POST",{nickName}) as any
      let userInfo = result.data.data[0]
      wx.setStorageSync("userInfo",userInfo)
      this.setData({
        name:""
      })
      this.init()
      wx.showToast({
        title:"修改成功",
        icon:"success"
      })
    }else{
      wx.showToast({
        title:"信息未修改",
        icon:"error"
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.init()
  }
})